const { SchemaDirectiveVisitor } = require("graphql-tools");
const { defaultFieldResolver } = require("graphql");
const { AuthenticationError } = require("apollo-server-express");
const { verify } = require("../util/jwt");
const { jwtSecret } = require("../config/config.default");

class AuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (parent, args, context, info) {
      const token = context.token;
      const dataSources = context.dataSources;
      if (!token) {
        throw new AuthenticationError("未授权");
      }
      try {
        const decodeData = await verify(token, jwtSecret);
        const user = await dataSources.users.findById(decodeData.userId);
        context.user = user;
      } catch (error) {
        throw new AuthenticationError("未授权");
      }

      const result = await resolve.call(this, parent, args, context, info);
      return result;
    };
  }
}

module.exports = AuthDirective;
